#include <iostream>
#include "log.hpp"
#include "Init.hpp"
using namespace std;

extern Log log;

enum
{
    DIVZERO = 1,
    MODZERO,
    UNKOWN
};
Init init;
class Task
{
public:
    Task(int communication_sockfd, const string &clientip, const uint16_t &clientport)
        : _sockfd(communication_sockfd), _clientIP(clientip), _clientport(clientport)
    {
    }
    void run()
    {
        // 测试代码：收到消息后服务器会有自动回复
        char buffer[1024];

        ssize_t n = read(_sockfd, buffer, sizeof(buffer)); // 接收客户端发来的消息
        if (n > 0)
        {
            buffer[n] = '\0';
            cout << "client key:" << buffer << endl;

            // 将处理后的消息（加前缀）回发给客户端
            string reply = init.translation(buffer);
            n = write(_sockfd, reply.c_str(), reply.size());
            if (n < 0)
            {
                log(Warning, "write error, errno; %d, errstring: %s", errno, strerror(errno));
            }
        }
        else if (n == 0)
        {
            log(Info, "%s:%d quit, server close sockfd: %d", _clientIP.c_str(), _clientport, _sockfd);
        }
        else
        {
            log(Warning, "read error, sockfd: %d", _sockfd);
        }
        close(_sockfd);
    }

    ~Task()
    {
    }

private:
    int _sockfd;
    string _clientIP;
    uint16_t _clientport;
};